package com.footballclub;

import com.footballclub.model.Finance;
import com.footballclub.model.Games;
import com.footballclub.model.Player;
import com.footballclub.model.User;

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

public class Main {
    // 文件路径（统一相对路径格式）
    private static final String USER_FILE = "untitled/data/user.txt";
    private static final String SHELF_FILE = "untitled/data/salaryInfo.txt";
    private static final String MATERIAL_FILE = "untitled/data/clubFinance.txt";
    private static final String PLAYER_FILE = "untitled/data/playerInfo.txt"; // 使用用户指定的绝对路径

    private static List<User> users = new ArrayList<>();
    private static List<Player> players = new ArrayList<>();
    private static List<Finance> finances = new ArrayList<>();

    private static User currentUser = null;
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        // 初始化时加载所有数据文件
        loadUsersFromFile();
        loadPlayersFromFile();
        loadFinanceFromFile();
        while (true) {
            if (currentUser == null) {
                showLoginOrRegisterMenu();
                String choice = scanner.nextLine();
                handleLoginOrRegister(choice);
            } else {
                showMainMenu();
                String choice = scanner.nextLine();
                handleMainMenu(choice);
            }
        }
    }

    private static void showLoginOrRegisterMenu() {
        System.out.println("\n-------足球俱乐部管理系统-------");
        System.out.println("| 1-登录");
        System.out.println("| 2-注册");
        System.out.println("| 3-退出");
        System.out.print("| 请输入您想要进行的操作：");
    }

    private static void handleLoginOrRegister(String choice) {
        switch (choice) {
            case "1":
                login();
                break;
            case "2":
                register();
                break;
            case "3":
                System.out.println("👋 退出系统！");
                System.exit(0);
            default:
                System.out.println("❌ 无效选择！");
        }
    }

    private static void login() {
        while (true) {
            System.out.println("\n-------欢迎登录俱乐部系统-------");
            System.out.println("| 1-登录信息输入");
            System.out.println("| 2-返回登录页面");
            System.out.print("| 请输入您想要进行的操作：");
            String choice = scanner.nextLine();

            if ("2".equals(choice)) {
                return;
            } else if ("1".equals(choice)) {
                System.out.print("请输入用户名: ");
                String username = scanner.nextLine();
                System.out.print("请输入密码: ");
                String password = scanner.nextLine();

                for (User user : users) {
                    if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
                        currentUser = user;
                        System.out.println("✅ 登录成功！欢迎您，" + user.getUsername() + "！");
                        return;
                    }
                }
                System.out.println("❌ 用户名或密码错误！");
            } else {
                System.out.println("❌ 无效选择！");
            }
        }
    }

    private static void register() {
        while (true) {
            System.out.println("\n-------俱乐部账号注册-------");
            System.out.println("|1-填写注册信息|");
            System.out.println("| 2-返回登录页面");
            System.out.print("| 请输入您想要进行的操作：|");
            String choice = scanner.nextLine();

            if ("2".equals(choice)) {
                return;
            } else if ("1".equals(choice)) {
                System.out.print("请输入用户名: ");
                String username = scanner.nextLine();
                System.out.print("请输入密码: ");
                String password = scanner.nextLine();

                // 检查用户名是否已存在
                for (User user : users) {
                    if (user.getUsername().equals(username)) {
                        System.out.println("已存在此用户，将返回注册界面。");
                        return;
                    }
                }

                // 创建新用户并保存
                User newUser = new User(username, password, "普通用户"); // 补充用户类型默认值
                users.add(newUser);
                saveNewUserToFile(newUser);
                System.out.println("✅ 注册成功！已使用该用户登录。");
                currentUser = newUser;
                return;
            } else {
                System.out.println("选择错误");
            }
        }
    }

    private static void saveNewUserToFile(User user) {
        // 确保数据目录存在
        File file = new File(USER_FILE);
        file.getParentFile().mkdirs();

        boolean userExists = false;

        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.startsWith(user.getUsername() + "/")) {
                        userExists = true;
                        break;
                    }
                }
            } catch (IOException e) {
                System.err.println("⚠️ 读取用户文件失败: " + e.getMessage());
            }
        }

        if (!userExists) {
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
                writer.write(user.getUsername() + "/" + user.getPassword() + "/" + user.getPlayer()); // 修正属性名与User类对应
                writer.newLine();
            } catch (IOException e) {
                System.err.println("❌ 保存用户失败: " + e.getMessage());
            }
        }
    }

    // 加载用户数据
    private static void loadUsersFromFile() {
        File file = new File(USER_FILE);
        if (!file.exists()) return;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("/");
                if (parts.length == 3) {
                    users.add(new User(parts[0], parts[1], parts[2]));
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 加载用户文件失败: " + e.getMessage());
        }
    }

    // 加载球员数据
    private static void loadPlayersFromFile() {
        File file = new File(PLAYER_FILE);
        if (!file.exists()) return;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split("-");
                if (parts.length == 4) {
                    Player player = new Player(parts[0],parts[1], parts[2], Integer.parseInt(parts[3]));
                    players.add(player);
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 加载球员文件失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.err.println("⚠️ 薪资格式转换失败: " + e.getMessage());
        }
    }

    // 加载财务数据
    private static void loadFinanceFromFile() {
        File file = new File(MATERIAL_FILE);
        if (!file.exists()) return;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 假设财务数据格式处理
                String[] parts = line.split(",");
                if (parts.length >= 1) {
                    Finance finance = new Finance();
                    // 根据实际Finance类属性设置
                    finances.add(finance);
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 加载财务文件失败: " + e.getMessage());
        }
    }

    private static void showMainMenu() {
        System.out.println("\n-------欢迎进入[俱乐部名称]管理中心-------");
        System.out.println("|1-球员管理|");
        System.out.println("|2-参赛管理|");
        System.out.println("|3-营收查询统计|");
        System.out.println("|4-登出|");
        System.out.print("| 请输入您想要进行的操作：");
    }

    private static void handleMainMenu(String choice) {
        switch (choice) {
            case "1":
                matchingMechanism();
                break;
            case "2":
                competitionManagement();
                break;
            case "3":
                inquiryStatistics(); // 修正方法名拼写
                break;
            case "4":
                currentUser = null;
                System.out.println("返回登录页面。");
                break;
            default:
                System.out.println("❌ 无效选择！");
        }
    }



    // 待完善部分
    private static void matchingMechanism() {
        while (true) {
            System.out.println("|******球员管理中心******|");
            System.out.println("|1-球员信息管理|");
            System.out.println("|2-球员薪资管理|");
            System.out.println("|3-返回主界面|");
            System.out.println("|请输入您想要进行的操作：");
            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    showTotalSalary();
                    break;
                case "2":
                    salaryInformation();
                    break;
                case "3":
                    return; // 直接返回，不调用showMainMenu()因为它会在调用方法中显示
                default:
                    System.out.println("❌ 无效选择！");
            }
        }
    }




    // 球员管控中心
    private static void showTotalSalary() {
        File file = new File(PLAYER_FILE);
        while (true) {
            System.out.println("|******球员信息中心******|");
            System.out.println("|1-球员列表|");
            System.out.println("|2-增加球员|");
            System.out.println("|3-删除球员|");
            System.out.println("|4-修改球员信息|");
            System.out.println("|5-查询球员|");
            System.out.println("|6-返回主界面|");
            System.out.println("|请输入您想要进行的操作：");
            String choice = scanner.nextLine();

//            xzh方法名自己该
            switch (choice) {
                case "1":
//                    //球员列表
                    showPlayer();
                    break;
                case "2":
//                    //增加球员
                    addPlayer();
                    break;
                case "3":
//                    //删除球员
                    deletePlayer();
                    break;
                case "4":
//                    //修改球员信息
                    updatePlayer();
                    break;
                case "5":
//                    //查询球员
                    queryPlayer();
                    break;
                case "6":
                     // 直接返回，不调用showMainMenu()因为它会在调用方法中显示
                    showMainMenu();
                default:
                    System.out.println("❌ 无效选择！");
            }
        }
    }



    // 显示球员列表
    private static void showPlayer() {
        if (players.isEmpty()) {
            System.out.println("📋 球员列表为空");
            return;
        }

        System.out.println("📋 球员列表:");
        for (Player player : players) {
            System.out.println(player);
        }
    }

    // 增加球员
    private static void addPlayer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入球员ID: ");
        String playerId = scanner.nextLine();
        System.out.print("请输入球员姓名: ");
        String playerName = scanner.nextLine();
        System.out.print("请输入球员位置: ");
        String position = scanner.nextLine();
        System.out.print("请输入球员薪水: ");
        int salary = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        Player player = new Player(playerId, playerName, position, salary);
        players.add(player);
        
        // 将球员信息写入文件
        try {
            // 确保数据目录存在
            File file = new File(PLAYER_FILE);
            file.getParentFile().mkdirs(); // 确保目录存在
            
            // 以追加模式写入文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
                writer.write(playerId + "-" + playerName + "-" + position + "-" + salary);
                writer.newLine();
            }
            
            System.out.println("✅ 球员已添加并保存到文件: " + PLAYER_FILE);
        } catch (IOException e) {
            System.err.println("❌ 保存球员信息到文件失败: " + e.getMessage());
            System.err.println("文件路径: " + PLAYER_FILE);
            System.out.println("✅ 球员已添加到内存但未保存到文件");
        }
    }

    // 删除球员
    private static void deletePlayer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入球员ID: ");
        String playerId = scanner.nextLine();

        Iterator<Player> iterator = players.iterator();
        while (iterator.hasNext()) {
            Player player = iterator.next();
            if (player.getPlayerId().equals(playerId)) {
                iterator.remove();
                System.out.println("✅ 球员已删除");
                return;
            }
        }
        System.out.println("❌ 未找到该球员");
    }

    //修改球员信息
    private static void updatePlayer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入球员ID: ");
        String playerId = scanner.nextLine();

        for (Player player : players) {
            if (player.getPlayerId().equals(playerId)) {
                System.out.print("请输入新姓名: ");
                String newName = scanner.nextLine();
                System.out.print("请输入球员位置: ");
                String newPosition = scanner.nextLine(); // 新增位置更新
                System.out.print("请输入新薪水: ");
                int newSalary = scanner.nextInt();

                player.setPlayerName(newName);
                player.setPosition(newPosition); // 新增位置设置
                player.setSalary(newSalary);
                System.out.println("✅ 球员信息已更新");
                return;
            }
        }
        System.out.println("❌ 未找到该球员");
    }

    // 查询球员
    private static void queryPlayer() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入球员ID: ");
        String playerId = scanner.nextLine();

        for (Player player : players) {
            if (player.getPlayerId().equals(playerId)) {
                System.out.println("球员信息: " + player);
                return;
            }
        }
        System.out.println("❌ 未找到该球员");
    }


    //参赛管理
    private static void competitionManagement() {
        while (true) {
            System.out.println("|******俱乐部参赛中心******|");
            System.out.println("|1-查看预定义参赛组|");
            System.out.println("|2-选择参赛组参赛|");
            System.out.println("|3-查看比赛记录|");
            System.out.println("|4-返回主界面|");
            System.out.println("|请输入您想要进行的操作：");
            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    showGameGroup();
                    break;
                case "2":
                    selectGameGroup();
                    break;
                case "3":
                    showGameRecord();
                    break;
                case "4":
                    return; // 直接返回，不调用showMainMenu()因为它会在调用方法中显示
                default:
                    System.out.println("❌ 无效选择！");
            }
        }

    }


    //查看预定义参赛组
    private static void showGameGroup() {
        // 定义playerGroup.text文件路径
        File file = new File("untitled/data/playerGroup.text");

        // 检查文件是否存在
        if (!file.exists()) {
            System.out.println("❌ 参赛组文件不存在！");
            return;
        }
        
        // 用于存储队伍和对应球员的映射
        Map<String, List<String>> teamPlayersMap = new HashMap<>();
        
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过空行
                line = line.trim();
                if (line.isEmpty()) continue;
                
                // 解析行数据，格式为：队伍名称/球员名称
                String[] parts = line.split("/");
                if (parts.length == 2) {
                    String teamName = parts[0].trim();
                    String playerName = parts[1].trim();
                    
                    // 将球员添加到对应队伍
                    teamPlayersMap.putIfAbsent(teamName, new ArrayList<>());
                    teamPlayersMap.get(teamName).add(playerName);
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 读取参赛组文件失败: " + e.getMessage());
            return;
        }
        
        // 显示所有参赛组信息
        if (teamPlayersMap.isEmpty()) {
            System.out.println("📋 暂无参赛组信息");
            return;
        }
        
        System.out.println("📋 预定义参赛组信息:");
        
        // 遍历每个队伍（参赛组）
        for (Map.Entry<String, List<String>> entry : teamPlayersMap.entrySet()) {
            String teamName = entry.getKey();
            List<String> players = entry.getValue();
            
            System.out.println("🏆 参赛组名称: " + teamName);
            System.out.println("👥 参赛球员:");
            
            // 显示该队伍的所有球员
            for (int i = 0; i < players.size(); i++) {
                System.out.println("   " + (i + 1) + ". " + players.get(i));
            }
            
        }
    }

    //选择参赛组参赛
    private static void selectGameGroup() {
        // 定义文件路径
        String clubFile = "untitled/data/club.txt";
        String gameResultFile = "untitled/data/gameResult.text";
        
        // 读取所有队伍
        List<String> teams = loadTeamsFromFile(clubFile);
        if (teams.isEmpty()) {
            System.out.println("❌ 俱乐部文件中没有队伍信息！");
            return;
        }
        
        System.out.println("⚽ 开始比赛流程...");
        System.out.println("📋 参赛队伍: " + String.join(", ", teams));
        
        // 开始比赛流程，决出冠军
        String champion = startTournament(teams, gameResultFile);
        
        // 宣布冠军
        System.out.println("\n🎉🏆 恭喜 " + champion + " 获得冠军！🏆🎉");
        System.out.println("📋 所有比赛结果已记录到 gameResult.text");
    }
    
    // 从club.txt文件加载队伍
    private static List<String> loadTeamsFromFile(String filePath) {
        List<String> teams = new ArrayList<>();
        File file = new File(filePath);
        
        if (!file.exists()) {
            System.out.println("❌ 俱乐部文件不存在！");
            return teams;
        }
        
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty()) {
                    teams.add(line);
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 读取俱乐部文件失败: " + e.getMessage());
        }
        
        return teams;
    }
    
    // 开始锦标赛流程
    private static String startTournament(List<String> teams, String resultFilePath) {
        List<String> currentTeams = new ArrayList<>(teams);
        
        while (currentTeams.size() > 1) {
            currentTeams = conductRound(currentTeams, resultFilePath);
        }
        
        return currentTeams.get(0);
    }
    
    // 进行一轮比赛
    private static List<String> conductRound(List<String> teams, String resultFilePath) {
        System.out.println("\n 🔁开始新一轮比赛...");
        System.out.println("📋 当前参赛队伍: " + String.join(", ", teams));
        
        List<String> winners = new ArrayList<>();
        List<String> remainingTeams = new ArrayList<>(teams);
        Random random = new Random();
        
        // 随机抽取两队进行比赛，直到所有队伍都被抽取
        while (!remainingTeams.isEmpty()) {
            // 随机抽取第一支队伍
            int index1 = random.nextInt(remainingTeams.size());
            String team1 = remainingTeams.remove(index1);
            
            // 随机抽取第二支队伍
            int index2 = random.nextInt(remainingTeams.size());
            String team2 = remainingTeams.remove(index2);
            
            // 进行比赛并获取胜者
            String winner = simulateAndRecordMatch(team1, team2, resultFilePath);
            winners.add(winner);
        }
        
        System.out.println("\n✅ 本轮比赛结束，获胜队伍: " + String.join(", ", winners));
        return winners;
    }
    
    // 模拟比赛并记录结果
    private static String simulateAndRecordMatch(String team1, String team2, String resultFilePath) {
        // 随机决定胜者
        Random random = new Random();
        String winner = random.nextBoolean() ? team1 : team2;

        // 构建比赛结果字符串
        String matchResult = team1 + " VS " + team2 + " | 胜者: " + winner;
        
        // 记录比赛结果
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFilePath, true))) {
            // 检查文件是否为空，如果不为空则添加换行符
            File file = new File(resultFilePath);
            if (file.length() > 0) {
                writer.newLine();
            }
            writer.write(matchResult);
        } catch (IOException e) {
            System.err.println("⚠️ 写入比赛结果失败: " + e.getMessage());
        }
        
        // 输出比赛结果
        System.out.println("\n⚔️ " + team1 + " VS " + team2);
        System.out.println("🏆 获胜队伍: " + winner);
        
        return winner;
    }


    private static void showGameRecord() {
        try (BufferedReader reader = new BufferedReader(new FileReader("untitled/data/gameResult.text"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("⚠️ 读取比赛记录文件失败: " + e.getMessage());
        }
    }


    // 球队薪资信息
    private static void salaryInformation() { // 修正方法名拼写
        while (true) {
            System.out.println("------球员薪资管理------");
            System.out.println("|1-球员信息列表|");
            System.out.println("|2-修改球员薪资|");
            System.out.println("|3-返回球员管理界面|");
            System.out.println("|请输入您想要进行的操作：");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    showPlayerSalary();
                    break;
                case "2":
                    updatePlayerSalary();
                    break;
                case "3":
                    // 返回主菜单而非登出
                    showMainMenu();
                default:
                    System.out.println("❌ 无效选择！");
            }
        }
    }

    private static void showPlayerSalary() {
        if (players.isEmpty()) {
            System.out.println("📋 球员信息列表为空");
            return;
        }

        System.out.println("📋 球员信息列表:");
        System.out.println("ID\t姓名\t薪资");
        for (Player player : players) {
            System.out.printf( 
                            player.getPlayerId(), 
                            player.getPlayerName(), 
                            player.getSalary());
        }

    }


    // 修改球员薪资信息
    private static void updatePlayerSalary() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入球员ID: ");
        String playerId = scanner.nextLine();

        for (Player player : players) {
            if (player.getPlayerId().equals(playerId)) {
                System.out.print("请输入新姓名: ");
                String newName = scanner.nextLine();
                System.out.print("请输入新薪水: ");
                int newSalary = scanner.nextInt();

                player.setSalary(newSalary);
                System.out.println("✅ 球员薪资已更新");
                return;
            }
        }
        System.out.println("❌ 未找到该球员");
    }

    // 周瀚霖 营收查询统计
    private static void inquiryStatistics() {
        while (true) {
            System.out.println("|******俱乐部营收统计******");
            System.out.println("|1-统计薪资总支出|");
            System.out.println("|2-返回主界面|");
            System.out.print("| 请输入您想要进行的操作：");
            String choice = scanner.nextLine();
            switch (choice) {
                case "1":
                    //推荐总支出方法
                    statisticalExpenditure();
                    //列adadad
                    break;
                case "2":
                    return; // 直接返回，避免菜单循环显示
                default:
                    System.out.println("❌ 无效选择！");
            }
        }
    }

    private static void statisticalExpenditure() {
        File file = new File(SHELF_FILE);
        if (!file.exists()) {
            System.out.println("❌ 薪资信息文件不存在！");
            return;
        }

        int totalSalary = 0; // 月薪资总支出
        int playerCount = 0; // 球员人数
        
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                // 解析薪资信息，格式为：俱乐部名称/球员名称/薪资
                String[] parts = line.split("/");
                if (parts.length == 3) {
                    try {
                        int salary = Integer.parseInt(parts[2].trim());
                        totalSalary += salary;
                        playerCount++;
                    } catch (NumberFormatException e) {
                        System.err.println("⚠️ 薪资格式错误: " + parts[2]);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("⚠️ 读取薪资文件失败: " + e.getMessage());
            return;
        }
        
        // 展示统计结果
        System.out.println("📊 当前统计周期：1个月");
        System.out.printf("当前俱乐部球员%d人，月薪资总支出：%d元，累计薪资支出（按1个月计）：%d元\n", playerCount, totalSalary, totalSalary);
    }



}